<!-- 正文开始 -->
<div class="layui-fluid" id="menuSearch">
    <div class="layui-card">
        <div class="layui-card-body">
            <div>
                <button class="layui-btn btnExpand" >全部展开</button>
                <button class="layui-btn btnFold" >全部折叠</button>
                <button class="layui-btn icon-btn btnSearch"><i class="layui-icon">&#xe615;</i>搜索</button>
                <button class="layui-btn btnAdd" ><i class="layui-icon layui-icon-add-1"></i>增加</button>
                <button class="layui-btn icon-btn btnSave layui-btn-normal"><i class="layui-icon layui-icon-ok"></i>保存</button>
            </div>
            <table id="menuTable" class="layui-table" lay-filter="menuTable"></table>
        </div>
    </div>

</div>

<!-- 操作列 -->
<script type="text/html" id="menuTable-operator">
    <a class="layui-btn layui-btn-primary layui-btn-xs {{d.isParent ? '':'layui-disabled'}}" lay-event="add">新增</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表格状态列 -->
<script type="text/html" id="tpl-menuTable-status">
    <input type="checkbox" lay-filter="tpl-menuTable-status" value="{{d.id}}" lay-skin="switch" lay-text="有效|无效"
           {{d.status==1?'checked':''}}/>
</script>

<!-- js部分 -->
<script>
    layui.use(['layer', 'form', 'table', 'treetable','http','tools','admin','element'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var treetable = layui.treetable;
        var http = layui.http;
        var tools = layui.tools;
        var admin = layui.admin;
        var element = layui.element;

        var viewId = "#menuSearch";
        var $view = $(viewId);

        // 渲染表格
        var menuTableIns = null;

        var fnSearch = function() {
            http.get('menu/list', {}, function (res) {
                if(res.ok) {
                    menuTableIns = treetable.render({
                        id: 'menuTable',
                        treeColIndex: 1,
                        treeSpid: 0,
                        treeIdName: 'id',
                        treePidName: 'parentId',
                        elem: '#menuTable',
                        data: res.data,
                        url: null,
                        page: false,
                        cellMinWidth: 50,
                        height: 'full-180',
                        cols: [[
                            {type: 'numbers'},
                            {field: 'name', title: '菜单名称', width: 200, edit: 'text'},
                            {field: 'url', title: '路径', width: 250, edit: 'text'},
                            {field: 'icon', title: '图标', width: 200, edit: 'text'},
                            {field: 'sort', align: 'center', title: '排序', width: 50, edit: 'text'},
                            {field: 'level', title: 'level', hide: true},
                            {
                                field: 'status',
                                title: '状态',
                                width: 80,
                                align: "center",
                                templet: "#tpl-menuTable-status"
                            },
                            {templet: "#menuTable-operator", width: 100, align: 'center', title: '操作'},
                            {field: 'updateTime', sort: false, title: '更新时间'},
                            {field: 'updateByWho', sort: false, title: '更新人'}
                        ]],
                        done: function () {
                            layer.closeAll('loading');
                        }
                    });
                }
            });
        };

        $view.find(".btnSearch").click(function(e){
            fnSearch();
        });
        var hasChilds = function(parentId){
            var data = menuTableIns.getCache();
            if(!data || data.length <= 0){ return false;}
            for(var i=0;i<data.length;i++){
                if(data[i].parentId === parentId && parentId !== 0){
                    return true;
                }
            }
            return false;
        };
        var findLastChildTr=function(trParent){
            var cache = menuTableIns.getCache();
            var nx = trParent.next();
            if(nx.length == 0){
                return trParent;
            }
            while(nx.length > 0) {
                var index = nx.attr("data-index");
                if(cache[index].isParent){
                    return nx.prev();
                }
                var tmp = nx;
                nx = nx.next();
                if(nx.length <= 0){
                    return tmp;
                }
            }
            return nx;
        };
        // 修改状态
        form.on('switch(tpl-menuTable-status)', function (obj) {
            var idx = obj.othis.parents("tr:eq(0)").attr("data-index");
            var data = {id: obj.elem.value, status: obj.elem.checked ? 1 : 0};
            menuTableIns.saveDelta(idx,data);
        });
        //监听工具条
        table.on('tool(menuTable)', function (rowObj) {
            var data = rowObj.data; //获得当前行数据
            var layEvent = rowObj.event; //获得 lay-event 对应的值

            if(layEvent === 'add') {
                if(!data.id){
                    http.failMsg("父菜单没有完整数据，请先保存");
                    return;
                }
                //var index = rowObj.tr.attr("data-index");
                var index = findLastChildTr(rowObj.tr).attr("data-index");
                var sort = menuTableIns.getCache()[index].sort +1;
                menuTableIns.addRow({name:'',pid:data.id, isParent:false, parentId:data.id, status:1, sort:sort},index);
            }
            else if (layEvent === 'edit') { //查看

            } else if (layEvent === 'del') { //删除
                if(hasChilds(data.id)){
                    http.failMsg("存在子项，不能删除");
                    return;
                }
                layer.confirm("确定删除该行?",{btn:["确定","取消"]},
                    function(index,obj) {
                        layer.closeAll('dialog');
                        rowObj.del();
                    }
                );
            }
        });

        table.on('edit(menuTable)',function (row) {
            var idx = row.tr.attr("data-index");
            var data = {};
            data.id = row.data.id;
            data[row.field] = row.value;
            menuTableIns.saveDelta(idx,data);
        });

        $view.find(".btnExpand").click(function () {
            treetable.expandAll('#menuTable');
        });

        $view.find(".btnFold").click(function () {
            treetable.foldAll('#menuTable');
        });

        $view.find(".btnAdd").click(function () {
            var sort = tools.getDataMax(menuTableIns.getCache(),"sort")+1;
            menuTableIns.addRow({id:0,pid:0,parentId:0,isParent:true,name:'',url:'',status:1,sort:sort});
            //tools.renderTable = renderTable;
            //fnOpenForm(true,{id:0,pid:0,isParent:true});
        });

        $view.find(".btnSave").click(function () {
            var data = menuTableIns.getDelta();
            if(!data){return;}
            http.post('menu/saveBatch',JSON.stringify(data),function(res){
                if(res.ok){
                    menuTableIns.updateCache(res.data);
                    menuTableIns.resetDelta();
                    http.okMsg(res.msg);
                }
            });
        });

        fnSearch();

        var fnOpenForm = function(isAdd,data){
            var mData = data;
            if(isAdd){
                mData = {};
                mData.parentId = data.id;
            }
            admin.putTempData('rowData', mData);
            admin.open({
                title: isAdd ? '新增菜单' : '修改菜单',
                url: http.viewPath + '/system/menuForm.html?v=1',
                area: ['600px', '350px'],
                success: function (layero, index) {
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');  // 禁止出现滚动条
                },
                end: function(){
                    tools.refs = null;
                    tools.renderTable = null;
                }
            });
        };
    });
</script>